import time

from selenium import webdriver
from selenium.common.exceptions import WebDriverException, InvalidArgumentException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from common.open_browser import open_browser


class Base:
    """
    封装了selenium基础方法,给case继承使用
    """

    def __init__(self, driver):
        # 初始化对象属性,设置driver
        self.driver = driver

    def get(self, url):
        # 请求网址
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('输入的网址不正确')

    def find_element(self, locator, timeout=10):
        # 定位元素 返回元素 使用显性等待
        try:
            return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator), '定位失败')
        except TimeoutException:
            print('定位失败')

    def click(self, locator):
        # 元素点击操作
        element = self.find_element(locator)
        if element:
            element.click()

    def get_attribute(self, locator, attr):
        # 获取元素属性
        element = self.find_element(locator)
        if element:
            return element.get_attribute(attr)  # 获取正确的属性值,获取不到就返回None

    def get_element_text(self, locator):
        # 获取元素文本
        element = self.find_element(locator)
        if element:
            return element.text

    def back(self):
        # 浏览器后退
        self.driver.back()

    def forward(self):
        # 浏览器前进
        self.driver.forward()

    def refresh(self):
        # 浏览器刷新
        self.driver.refresh()

    def quit(self, seconds=0):
        # 退出浏览器
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    driver = open_browser('chrome')  # 调用open_browser函数.打开浏览器,默认谷歌
    base = Base(driver)  # 设置Base对象,传入driver
    base.get('https://www.baidu.com')
    # base.find_element((By.ID, 'kw'))
    # print(base.get_attribute((By.ID, 'kw'), 'outerHTML'))
    print(base.get_attribute((By.ID, 'kw'), 'class'))
    base.quit(2)
